<template>
  <div class="box-border w-full h-full p-6">
    <div class="mb-6 text-xl font-bold text-center">运行方案报表</div>

    <!-- 当有数据时显示表格 -->
    <div v-if="hasData" class="scheme-table-container">
      <!-- 时间信息 -->
      <div class="mb-4 time-info">
        <span class="text-lg font-semibold">{{ currentScheme.time }}</span>
        <span class="ml-4 text-gray-600">方案 {{ currentPage }} / {{ totalPages }}</span>
      </div>

      <!-- 运行方案表格 -->
      <div class="table-wrapper">
        <table class="scheme-table">
          <thead>
            <tr>
              <th>站场</th>
              <th>配泵方案</th>
              <th>进站压力（MPa）</th>
              <th>出站压力（MPa）</th>
              <th>进站温度（℃）</th>
              <th>出站温度（℃）</th>
              <th>站场出站流量（m³/h）</th>
            </tr>
          </thead>
          <tbody>
            <tr
              v-for="station in currentScheme.stations"
              :key="station.name"
              :class="getStationRowClass(station.name)"
            >
              <td class="station-name">{{ station.name }}</td>
              <td class="pump-scheme">{{ station.pumpScheme }}</td>
              <td class="pressure-in">{{ station.pressureIn }}</td>
              <td class="pressure-out">{{ station.pressureOut }}</td>
              <td class="temp-in">{{ station.tempIn }}</td>
              <td class="temp-out">{{ station.tempOut }}</td>
              <td class="flow-out">{{ station.flowOut }}</td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- 分页控件 -->
      <div class="pagination-container">
        <div class="pagination">
          <button @click="previousPage" :disabled="currentPage === 1" class="page-btn prev-btn">
            上一页
          </button>

          <div class="page-numbers">
            <button
              v-for="page in visiblePages"
              :key="page"
              @click="goToPage(page)"
              :class="['page-number', { active: page === currentPage }]"
            >
              {{ page }}
            </button>
          </div>

          <button
            @click="nextPage"
            :disabled="currentPage === totalPages"
            class="page-btn next-btn"
          >
            下一页
          </button>
        </div>

        <!-- 跳转到指定页面 -->
        <div class="jump-to-page">
          <span class="jump-label">跳转到</span>
          <input
            v-model.number="jumpPageInput"
            @keyup.enter="jumpToPage"
            type="number"
            :min="1"
            :max="totalPages"
            class="jump-input"
            placeholder="页码"
          />
          <span class="jump-label">页</span>
          <button @click="jumpToPage" class="jump-btn">确定</button>
        </div>
      </div>
    </div>

    <!-- 当没有数据时显示提示 -->
    <div v-else class="no-scheme-container">
      <div class="no-scheme-message">
        <div class="icon">⚠️</div>
        <div class="text">无启泵运行方案</div>
        <div class="sub-text">当前条件下无法生成启泵运行方案，请检查系统参数设置</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'

const props = defineProps({
  tableData: {
    type: Array,
    required: false,
    default: () => []
  },
  ganttData: {
    type: Object,
    required: false,
    default: null
  },
  timeInterval: {
    type: [String, Number],
    required: false,
    default: 10
  }
})

// 是否有数据
const hasData = computed(() => {
  return props.tableData && props.tableData.length > 0
})

// 当前页码
const currentPage = ref(1)

// 跳转页面输入值
const jumpPageInput = ref('')

// 根据ganttData获取配泵方案
const getPumpScheme = (stationName, timeValue) => {
  if (!props.ganttData || !props.ganttData.series) {
    return '--'
  }

  // 根据站场名称找到对应的泵
  const pumpMap = {
    乌尔禾站: ['乌-1', '乌-2', '乌-3'],
    百克站: ['百-1', '百-2', '百-3'],
    '81#站': ['81#-1', '81#-2', '81#-3']
  }

  const pumps = pumpMap[stationName] || []
  const activePumps = []

  pumps.forEach((pumpName) => {
    const pump = props.ganttData.series.find((s) => s.name === pumpName)
    if (pump && pump.intervals && pump.intervals.length > 0) {
      // 检查当前时间是否在任何一个开启区间内（intervals中的时间单位是小时，需要转换为分钟）
      const isActive = pump.intervals.some((interval) => {
        const [startHours, endHours] = interval
        const startMinutes = startHours * 60
        const endMinutes = endHours * 60
        // 使用分钟比较
        return timeValue >= startMinutes && timeValue <= endMinutes
      })

      if (isActive) {
        // 提取泵编号（如"乌-1" -> "1"）
        const pumpNumber = pumpName.split('-')[1]
        activePumps.push(pumpNumber + '#')
      }
    }
  })

  // 调试信息
  if (timeValue === 0) {
    console.log(`调试 ${stationName} 在时间 ${timeValue}min:`, {
      pumps,
      activePumps,
      ganttData: props.ganttData.series.filter((s) => pumps.includes(s.name))
    })
  }

  return activePumps.length > 0 ? activePumps.join('、') + '泵开启' : '--'
}

// 从props.tableData生成运行方案数据
const schemes = computed(() => {
  if (!props.tableData || props.tableData.length === 0) return []

  // 直接使用tableData，不根据timeInterval改变
  return props.tableData.map((item, index) => {
    const timeValue = item.time || index * (parseInt(props.timeInterval) || 10)

    return {
      time: `时间: ${timeValue} min`,
      stations: [
        {
          name: '乌尔禾站',
          pumpScheme: getPumpScheme('乌尔禾站', timeValue),
          pressureIn: '--',
          pressureOut: item.p_out_weh?.toFixed(3) || '--',
          tempIn: '--',
          tempOut: item.t_out_weh?.toFixed(2) || '--',
          flowOut: item.q_wbx?.toFixed(2) || '--'
        },
        {
          name: '百克站',
          pumpScheme: getPumpScheme('百克站', timeValue),
          pressureIn: item.p_in_bkz?.toFixed(3) || '--',
          pressureOut: item.p_out_bkz?.toFixed(3) || '--',
          tempIn: item.t_in_bkz?.toFixed(2) || '--',
          tempOut: item.t_out_bkz?.toFixed(2) || '--',
          flowOut: item.q_bkx?.toFixed(2) || '--'
        },
        {
          name: '701站',
          pumpScheme: '--',
          pressureIn: item.p_in_701?.toFixed(3) || '--',
          pressureOut: item.p_out_701?.toFixed(3) || '--',
          tempIn: item.t_in_701?.toFixed(2) || '--',
          tempOut: item.t_out_701?.toFixed(2) || '--',
          flowOut: item.q_701_zz?.toFixed(2) || '--'
        },
        {
          name: '总站',
          pumpScheme: '--',
          pressureIn: item.p_in_zz?.toFixed(3) || '--',
          pressureOut: '--',
          tempIn: item.t_in_zz?.toFixed(2) || '--',
          tempOut: '--',
          flowOut: '--'
        },
        {
          name: '81#站',
          pumpScheme: getPumpScheme('81#站', timeValue),
          pressureIn: item.p_in_81?.toFixed(3) || '--',
          pressureOut: item.p_out_81?.toFixed(3) || '--',
          tempIn: item.t_in_81?.toFixed(2) || '--',
          tempOut: item.t_out_81?.toFixed(2) || '--',
          flowOut: item.q_81_701?.toFixed(2) || '--'
        }
      ]
    }
  })
})

// 总页数
const totalPages = computed(() => schemes.value.length)

// 当前方案
const currentScheme = computed(() => schemes.value[currentPage.value - 1])

// 可见页码
const visiblePages = computed(() => {
  const pages = []
  const total = totalPages.value
  const current = currentPage.value

  if (total <= 5) {
    for (let i = 1; i <= total; i++) {
      pages.push(i)
    }
  } else {
    if (current <= 3) {
      for (let i = 1; i <= 5; i++) {
        pages.push(i)
      }
    } else if (current >= total - 2) {
      for (let i = total - 4; i <= total; i++) {
        pages.push(i)
      }
    } else {
      for (let i = current - 2; i <= current + 2; i++) {
        pages.push(i)
      }
    }
  }

  return pages
})

// 分页方法
const previousPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
  }
}

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
  }
}

const goToPage = (page) => {
  currentPage.value = page
}

// 跳转到指定页面
const jumpToPage = () => {
  const page = parseInt(jumpPageInput.value)
  if (page && page >= 1 && page <= totalPages.value) {
    currentPage.value = page
    jumpPageInput.value = ''
  } else {
    // 输入无效时清空输入框
    jumpPageInput.value = ''
  }
}

// 获取站场行样式类
const getStationRowClass = (stationName) => {
  const classMap = {
    乌尔禾站: 'wuerhe-row',
    百克站: 'baike-row',
    '701站': 'station701-row',
    总站: 'main-station-row',
    '81#站': 'station81-row'
  }
  return classMap[stationName] || ''
}

// 监听tableData变化，重置页码
watch(
  () => props.tableData,
  () => {
    currentPage.value = 1
  },
  { deep: true }
)
</script>

<style lang="scss" scoped>
.scheme-table-container {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 24px;
}

.time-info {
  display: flex;
  align-items: center;
  padding: 16px 0;
  border-bottom: 2px solid #f0f0f0;
}

.table-wrapper {
  overflow-x: auto;
  margin: 20px 0;
}

.scheme-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;

  th {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 16px 12px;
    text-align: center;
    font-weight: 600;
    border: 1px solid #ddd;
    white-space: nowrap;

    &:first-child {
      border-top-left-radius: 8px;
    }

    &:last-child {
      border-top-right-radius: 8px;
    }
  }

  td {
    padding: 14px 12px;
    text-align: center;
    border: 1px solid #e0e0e0;
    transition: background-color 0.3s ease;
  }

  tbody tr {
    &:hover {
      background-color: rgba(102, 126, 234, 0.05);
    }

    &:last-child td {
      &:first-child {
        border-bottom-left-radius: 8px;
      }

      &:last-child {
        border-bottom-right-radius: 8px;
      }
    }
  }
}

// 站场行样式
.wuerhe-row {
  background: rgba(70, 120, 178, 0.05);

  .station-name {
    background: rgba(70, 120, 178, 0.1);
    color: #4678b2;
    font-weight: 600;
  }
}

.baike-row {
  background: rgba(231, 76, 60, 0.05);

  .station-name {
    background: rgba(231, 76, 60, 0.1);
    color: #e74c3c;
    font-weight: 600;
  }
}

.station701-row {
  background: rgba(52, 152, 219, 0.05);

  .station-name {
    background: rgba(52, 152, 219, 0.1);
    color: #3498db;
    font-weight: 600;
  }
}

.main-station-row {
  background: rgba(155, 89, 182, 0.05);

  .station-name {
    background: rgba(155, 89, 182, 0.1);
    color: #9b59b6;
    font-weight: 600;
  }
}

.station81-row {
  background: rgba(39, 174, 96, 0.05);

  .station-name {
    background: rgba(39, 174, 96, 0.1);
    color: #27ae60;
    font-weight: 600;
  }
}

// 分页样式
.pagination-container {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16px;
  margin-top: 24px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

.pagination {
  display: flex;
  align-items: center;
  gap: 8px;
}

.page-btn {
  padding: 8px 16px;
  border: 1px solid #ddd;
  background: white;
  color: #666;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover:not(:disabled) {
    background: #667eea;
    color: white;
    border-color: #667eea;
  }

  &:disabled {
    background: #f5f5f5;
    color: #ccc;
    cursor: not-allowed;
  }
}

.page-numbers {
  display: flex;
  gap: 4px;
}

.page-number {
  width: 40px;
  height: 40px;
  border: 1px solid #ddd;
  background: white;
  color: #666;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;

  &:hover {
    background: #667eea;
    color: white;
    border-color: #667eea;
  }

  &.active {
    background: #667eea;
    color: white;
    border-color: #667eea;
    font-weight: 600;
  }
}

// 跳转页面样式
.jump-to-page {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;

  .jump-label {
    font-size: 14px;
    color: #666;
    white-space: nowrap;
  }

  .jump-input {
    width: 60px;
    height: 32px;
    padding: 0 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
    text-align: center;
    font-size: 14px;
    outline: none;
    transition: border-color 0.3s ease;

    &:focus {
      border-color: #667eea;
      box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
    }

    &::-webkit-outer-spin-button,
    &::-webkit-inner-spin-button {
      -webkit-appearance: none;
      margin: 0;
    }

    &[type='number'] {
      -moz-appearance: textfield;
      appearance: textfield;
    }
  }

  .jump-btn {
    padding: 6px 12px;
    background: #667eea;
    color: white;
    border: none;
    border-radius: 4px;
    font-size: 14px;
    cursor: pointer;
    transition: background-color 0.3s ease;

    &:hover {
      background: #5a6fd8;
    }

    &:active {
      background: #4e5bc6;
    }
  }
}

// 无方案提示样式
.no-scheme-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400px;
}

.no-scheme-message {
  text-align: center;
  padding: 40px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

  .icon {
    font-size: 48px;
    margin-bottom: 16px;
  }

  .text {
    font-size: 24px;
    font-weight: 600;
    color: #e74c3c;
    margin-bottom: 12px;
  }

  .sub-text {
    font-size: 16px;
    color: #666;
    line-height: 1.5;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .scheme-table {
    font-size: 12px;

    th,
    td {
      padding: 8px 6px;
    }
  }

  .time-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .pagination {
    flex-wrap: wrap;
    justify-content: center;
  }

  .jump-to-page {
    flex-wrap: wrap;
    justify-content: center;
    gap: 6px;

    .jump-input {
      width: 50px;
    }
  }
}
</style>
